package day_2022_12_to_3.year2023;

/**
 * @author haomin
 * @date 2023/01/04 22:23
 **/
public class Day1_4_Num1802 {
    class Solution {
        public int maxValue(int n, int index, int maxSum) {
            long l = 1, r = maxSum;
            while(l < r) {
                long mid = l + r + 1 >> 1;
                if(check(mid, n, index, maxSum)) {
                    l = mid;
                }else {
                    r = mid - 1;
                }
            }
            return (int) l;
        }
        public boolean check(long mid, int n, int index, int maxSum) {
            long sum = mid;
            int right = n - 1 - index, left = index;
            if(right <= mid - 1) sum += (mid - 1 + mid - right) * right / 2;
            else sum += mid  * (mid - 1) / 2 + (right - mid + 1);
            if(left <= mid - 1) sum += (mid - 1 + mid - left) * left / 2;
            else sum += mid  * (mid - 1) / 2 + (left - mid + 1);
            return sum <= maxSum;
        }
    }
}